package com.csstu.tomcat.handler;

import com.csstu.tomcat.CsTomcat;
import com.csstu.tomcat.http.CsRequest;
import com.csstu.tomcat.http.CsResponse;
import com.csstu.tomcat.servlet.CsHttpServlet;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @program: cstomcat
 * @description: http请求处理线程
 * @author: 程硕
 * @create: 2025-08-16 20:20
 **/
public class CsRequestHandler implements Runnable{
    // 定义Socket
    private Socket socket;
    // 构造方法
    public CsRequestHandler(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            //InputStream inputStream = socket.getInputStream();

            CsRequest request = new CsRequest(socket.getInputStream());

            //String num1 = request.getParameter("num1");
            //String num2 = request.getParameter("num2");
            //
            //System.out.println("请求的参数num1: "+num1);
            //System.out.println("请求的参数num2: "+num2);


            CsResponse response = new CsResponse(socket.getOutputStream());
            //OutputStream outputStream = csResponse.getOutputStream();
            //String resp = CsResponse.responseHead + "<h1> csResp 返回的信息 hi 你好</h1>";
            //
            //outputStream.write(resp.getBytes());
            //outputStream.flush();
            //outputStream.close();
            //CsCalServlet csCalServlet = new CsCalServlet();
            //csCalServlet.doGet(request, csResponse);

            //实现思路
            /*
            * 在request 对象中获取uri
            * 拿到uri 反射创建对象
            * 执行父类 CsHttpServlet 的service方法
            * */
            String uri = request.getUri();
            String servletName = CsTomcat.servletUrlMapping.get(uri);
            if (servletName == null){
                servletName = "";
            }
            CsHttpServlet httpServlet = CsTomcat.servletMapping.get(servletName);
            if (httpServlet != null){
                httpServlet.service(request, response);
            }else {
                OutputStream outputStream = response.getOutputStream();
                String resp = CsResponse.responseHead + "<h1> 404 not found</h1>";
                outputStream.write(resp.getBytes());
                outputStream.flush();
                outputStream.close();
            }

            //try {
            //    Class<?> aClass = Class.forName("com.csstu.tomcat.servlet." + uri);
            //    CsServlet servlet = (CsServlet) aClass.newInstance();
            //    servlet.service(request, csResponse);
            //} catch (Exception e) {
            //    throw new RuntimeException(e);
            //}
            //inputStream.close();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
